import React, { useState, useEffect } from 'react';
import { apiService } from '../services/api';
import websocketService from '../services/websocket';
import MetricSection from './MetricSection';
import TrodeList from './TrodeList';
import PageHeader from './PageHeader';
import { ArrowPathIcon } from '@heroicons/react/24/outline';
import { CuboxButton } from './ui';

const Dashboard = () => {
  const [chartData, setChartData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [lastUpdate, setLastUpdate] = useState(null);
  const [connectionStatus, setConnectionStatus] = useState('disconnected');

  const handleChartsUpdate = (data) => {
    setChartData(data);
    setLastUpdate(new Date());
  };

  const handleRefresh = async () => {
    setLoading(true);
    try {
      const chartsData = await apiService.getCharts();
      setChartData(chartsData);
      setLastUpdate(new Date());
      setError(null);
    } catch (err) {
      setError('Failed to load dashboard data');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // Initial data load
    handleRefresh();

    // Set up WebSocket connection
    websocketService.connect();

    // Set up message handlers
    websocketService.onMessage('charts_update', handleChartsUpdate);

    // Monitor connection status
    const checkConnection = () => {
      setConnectionStatus(websocketService.getConnectionState());
    };

    const connectionInterval = setInterval(checkConnection, 1000);

    // Cleanup on unmount
    return () => {
      clearInterval(connectionInterval);
      websocketService.offMessage('charts_update', handleChartsUpdate);
      websocketService.disconnect();
    };
  }, []);

  if (loading && !chartData) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading dashboard...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="text-center">
          <div className="text-red-600 text-lg font-medium mb-4">{error}</div>
          <button
            onClick={handleRefresh}
            className="px-4 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 transition-colors"
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  // Calculate averages from chart data
  const avgCPU  = chartData?.cpu?.values?.at(-1) ?? 0;
  const avgMem  = chartData?.memory?.values?.at(-1) ?? 0;
  const avgDisk = chartData?.disk?.values?.at(-1) ?? 0;

  const formatLastUpdate = (date) => {
    if (!date) return '-';
    return date.toLocaleTimeString();
  };

  const getConnectionStatusColor = (status) => {
    switch (status) {
      case 'connected':
        return 'bg-green-100 text-green-800 border border-green-200';
      case 'connecting':
        return 'bg-yellow-100 text-yellow-800 border border-yellow-200';
      case 'disconnected':
        return 'bg-red-100 text-red-800 border border-red-200';
      default:
        return 'bg-gray-100 text-gray-800 border border-gray-200';
    }
  };

  const getConnectionStatusText = (status) => {
    switch (status) {
      case 'connected':
        return 'Live';
      case 'connecting':
        return 'Connecting...';
      case 'disconnected':
        return 'Disconnected';
      default:
        return 'Unknown';
    }
  };

  return (
    <div className="min-h-screen bg-gray-100">
      <PageHeader>
        <div className="flex items-center space-x-4">
          <span className={`px-3 py-1 text-xs font-semibold rounded-full ${getConnectionStatusColor(connectionStatus)}`}>
            {getConnectionStatusText(connectionStatus)}
          </span>
          <div className="text-sm text-gray-600">
            <span className="font-medium">Last updated:</span>
            <span className="ml-2 font-mono text-gray-900">{formatLastUpdate(lastUpdate)}</span>
          </div>
          <CuboxButton
            onClick={handleRefresh}
            disabled={loading}
            width={140}
            style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}
          >
            <ArrowPathIcon 
              className={`w-4 h-4 mr-2 ${loading ? 'animate-spin' : ''}`} 
            />
            <span>Refresh</span>
          </CuboxButton>
        </div>
      </PageHeader>
      
      <main className="max-w-full mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Two Column Layout */}
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          {/* Left Column - Charts in 2x2 Grid */}
          <div className="lg:col-span-2">
            <div className="grid grid-cols-2 gap-6" style={{ height: '600px' }}>
              <MetricSection
                title="CPU Usage"
                color="emerald"
                iconPath="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z"
                chartId="cpu-chart"
                value={avgCPU}
                chartData={chartData?.cpu}
                showIO={false}
              />

              <MetricSection
                title="Memory Usage"
                color="amber"
                iconPath="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4"
                chartId="memory-chart"
                value={avgMem}
                chartData={chartData?.memory}
                showIO={false}
              />

              <MetricSection
                title="Disk Usage"
                color="violet"
                iconPath="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"
                chartId="disk-chart"
                value={avgDisk}
                chartData={chartData?.disk}
                showIO={false}
              />

              <MetricSection
                title="Network I/O"
                color="blue"
                iconPath="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"
                chartId="network-chart"
                networkData={chartData?.network}
                showIO={true}
              />
            </div>
          </div>

          {/* Right Column - Trode List */}
          <div className="lg:col-span-2">
            <TrodeList />
          </div>
        </div>
      </main>
    </div>
  );
};

export default Dashboard;